import java.net.*;
import java.io.*;
import java.util.*;

/*
 * Jason Lee (blujay)
 * EECS 382
 * P1T
 * TestClient.java - not for submission (stress test agent)
 */

public class TestClient {
	
	public static String prefix = "test";
	public static String ext = ".txt";
	
	public static void failed()
	{
        System.err.println("Submission unsuccessful");
        System.exit(1);
	}
	
	public static void write(String str)
	{
		PrintWriter out = null;
		try {
			out = new PrintWriter(str);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			failed();
		}
		Random randomGenerator = new Random();
		int x = randomGenerator.nextInt(1000);
		int y = randomGenerator.nextInt(500);
		for (int i = 0; i < x; i++)
		{
			for (int j = 0; j < y; j++)
			{
				if (j == y-1)
				{
					out.println(randomGenerator.nextInt(2));
				} else
				{
					out.print(randomGenerator.nextInt(2));
				}
			}
		}
		out.close();
	}
	
	public static void main (String [] args) throws IOException
	{
		if(args.length == 4)
		{
			System.err.println("Requires 4 inputs: host, port, user, number of rand files");
			failed();
		}
		Socket thisSocket = null;
		PrintWriter out = null;
		FileInputStream in = null;
		ArrayList<String> allFiles = null;
		int tempPntr = 0;
		int files = Integer.valueOf(args[3]);
		if (files < 0)
			failed();
		for ( ; tempPntr != files; tempPntr++)
		{
			String tempStr = prefix + Integer.toString(tempPntr) + ext;
			write(tempStr);
			allFiles.add(tempStr);
		}
		try
		{
        	thisSocket = new Socket(args[0],Integer.parseInt(args[1]));
            out = new PrintWriter(thisSocket.getOutputStream(), true);
            out.println(args[2]);
            out.println(files); // fix for file counting
            for (String thisFile : allFiles)
            {
            	File tempFile = new File(thisFile);
            	in = new FileInputStream(tempFile);
            	out.println(thisFile);
            	long size = tempFile.length();
            	out.println(size);
            	System.out.println("Submitting file " + args[tempPntr]);
            	for (long i = 0; i < size; i++)
            	{
            		out.println(in.read());
            	}
            }
            in.close();
			System.out.println("Submission successful: " + files + " files submitted");
		} catch (UnknownHostException e) {
            failed();
        } catch (IOException e) {
            failed();
        }
	}

}
